/*
 * @Descripttion:
 * @version:
 * @Author: caiailing
 * @Date: 2023-03-29 14:42:43
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-04-07 15:58:09
 */
import { isDevelopment, isH5 } from './platform'
import { forward } from './router/router'
import { getToken } from './auth'
import env from '@/config/env'
import { hideLoading, showLoading } from '@/config/serviceLoading'
import { useInit } from '@/hooks/useInit'
import { getCommonParams } from '@/config/commonParams'
type codeType = number | string
// 请求错误弹框提示 toke过期跳转登录页
function reject(err: { code: codeType; msg: string }) {
  const { msg = '异常，稍候片刻！', code = -1 } = err
  switch (code) {
    case '401':
      // 特殊异常处理
      forward('login')
      break
    default:
      uni.showToast({
        title: msg,
        icon: 'none'
      })
      break
  }
}
// h5环境开启代理
const apiBaseUrl = isH5 && isDevelopment ? '/api' : env.apiBaseUrl

function baseRequest(
  method:
    | 'OPTIONS'
    | 'GET'
    | 'HEAD'
    | 'POST'
    | 'PUT'
    | 'DELETE'
    | 'TRACE'
    | 'CONNECT'
    | undefined,
  url: string,
  data: { isLoading: any }
) {
  interface IheaderTpe {
    'content-type': string
    tme_Authorization?: string
  }
  let headers: IheaderTpe = {
    'content-type': 'application/json; charset=utf-8'
  }
  // 获得token类型
  const token: string = getToken()!
  // 请求返回code类型

  if (token) {
    headers = {
      'content-type': 'application/json; charset=utf-8',
      tme_Authorization: token
    }
  }
  return new Promise((resolve) => {
    showLoading(data.isLoading)
    delete data.isLoading
    let responseDate: unknown
    uni.request({
      url: apiBaseUrl + url,
      method,
      timeout: 20000,
      header: headers,
      data,
      success: (res: any) => {
        if (res.statusCode >= 200 && res.statusCode < 500) {
          if (res.data.code === '0000') {
            responseDate = res.data.data
          } else {
            // 无token
            if (res.data.code === '-1000') {
              forward('login')
            }
            if (res.data.code === '401') {
              const { pageName, pageQuery } = useInit()
              forward('login', {
                pageName,
                pageQuery: JSON.stringify(pageQuery)
              })
            }
            reject(res.data)
          }
        } else {
          reject({
            code: -1,
            msg: '异常，稍候片刻！'
          })
        }
      },
      fail: () => {
        reject({
          code: -1,
          msg: '网络不给力，请检查你的网络设置~'
        })
      },
      complete: (data) => {
        console.log('请求data', data)
        resolve(responseDate)
        hideLoading()
      }
    })
  })
}
// 请求参数加上接口请求状态
interface IrequestQuery {
  isLoading: Boolean
}
const http = {
  get: <T>(api: string, params: T & IrequestQuery) =>
    baseRequest('GET', api, {
      ...getCommonParams(),
      ...params
    }) as Http.Response,
  post: <T>(api: string, params: T & IrequestQuery) => {
    return baseRequest('POST', api, {
      ...getCommonParams(),
      ...params
    }) as Http.Response
  }
}

export default http
